import { modifyCourseStatus } from '../../js/modify_course_status.js'
window.onload = function () {
  let DESIGN_WIDTH = 1334
  let DESIGN_HEIGHT = 750
  // 初始化及基准rem的值
  document.documentElement.style.fontSize =
    (window.innerHeight * 12) / DESIGN_WIDTH + 'px'

  // 当前实验是否播放声音
  // let audioplay = true
  let audio
  let playing = {
    'background-image': 'url(../../images/播放着.png)',
    'background-size': '80%',
    'background-repeat': 'no-repeat',
    'background-position': 'center',
  }

  let toPlay = {
    'background-image': 'url(../../images/点击播放.png)',
    'background-size': '80%',
    'background-repeat': 'no-repeat',
    'background-position': 'center',
  }

  let currentAudioUrl = ''
  // pixijs
  let app, loader
  // 精灵变量
  let plate,
    temper,
    temper_button,
    zero_temper,
    hundred_temper,
    zero_line,
    hundred_line,
    temper_mask
  let tool_message

  // bump.js
  let b = new Bump(PIXI)
  // window
  let windowWidth = window.innerWidth
  let windowHeight = window.innerHeight
  // tink.js
  let tink
  let state = play

  // temper_button在点击时候的坐标差值
  let temperDeltaX, temperDeltaY

  function initApp() {
    app = new PIXI.Application({
      resolution: 3,
      width: windowWidth,
      height: windowHeight,
      autoDensity: true,
    })
    app.stage.sortableChildren = true
    app.renderer.backgroundColor = 0xfef6ef
    document.getElementById('main').appendChild(app.view)
    loader = new PIXI.Loader()
    loader.add([
      '../../images/rowimages_03/空盘子.png',
      '../../images/rowimages_03/有水的盘子.png',
      '../../images/rowimages_03/盘子和冰.png',
      '../../images/rowimages_03/盘子和融化的冰.png',
      '../../images/rowimages_03/水1.png',
      '../../images/rowimages_03/水2.png',
      '../../images/rowimages_03/水3.png',
      '../../images/rowimages_03/位置框.png',
      '../../images/rowimages_03/温度计.png',
      '../../images/rowimages_03/温度计滑块未选中状态.png',
      '../../images/rowimages_03/温度计滑块选中状态.png',
      '../../images/rowimages_03/刻度条.png',
    ])
    tink = new Tink(PIXI, app.view)

    setBackground()
    createPlateSprite()
    createTemperSprite()
    createTemperLine()
    createTemperButtonSprite()
    createZeroTempSprite()
    createHundredSprite()
    createToolMessage()
    createTemperMsek()
  }
  // 创建背景精灵
  function setBackground() {
    loader.load(setupBg)
    function setupBg() {
      let bgimage = new PIXI.Sprite(
        loader.resources['../../images/rowimages_03/位置框.png'].texture
      )
      bgimage.width = (windowWidth * 170) / DESIGN_HEIGHT
      bgimage.height = windowHeight
      bgimage.x = (windowWidth * 460) / DESIGN_HEIGHT
      app.stage.addChild(bgimage)
    }
  }

  // 创建盘子精灵
  function createPlateSprite() {
    loader.load(plateSetup)
    function plateSetup() {
      plate = new PIXI.Sprite(
        loader.resources['../../images/rowimages_03/盘子和冰.png'].texture
      )
      plate.width = (windowHeight * 250) / DESIGN_WIDTH
      plate.height = (windowWidth * 445) / DESIGN_HEIGHT
      plate.x = (windowWidth * 180) / DESIGN_HEIGHT
      plate.y = (windowHeight * 490) / DESIGN_WIDTH
      app.stage.addChild(plate)
    }
  }

  // 创建温度计的精灵
  function createTemperSprite() {
    loader.load(temperSetup)
    function temperSetup() {
      temper = new PIXI.Sprite(
        loader.resources['../../images/rowimages_03/温度计.png'].texture
      )
      temper.width = (windowWidth * 57) / DESIGN_HEIGHT
      temper.height = (windowHeight * 1100) / DESIGN_WIDTH
      temper.x = (windowWidth * 50) / DESIGN_HEIGHT
      temper.y = (windowHeight * 118) / DESIGN_WIDTH
      app.stage.addChild(temper)
    }
  }

  // 创建温度选择按钮的精灵
  function createTemperButtonSprite() {
    loader.load(temperBottonSetup)
    function temperBottonSetup() {
      temper_button = new PIXI.Sprite(
        loader.resources[
          '../../images/rowimages_03/温度计滑块未选中状态.png'
        ].texture
      )
      temper_button.buttonMode = true
      temper_button.interactive = false

      temper_button.width = (windowWidth * 78) / DESIGN_HEIGHT
      temper_button.height = (windowHeight * 50) / DESIGN_WIDTH
      temper_button.x = (windowWidth * 64) / DESIGN_HEIGHT
      temper_button.y = (windowHeight * 278) / DESIGN_WIDTH
      temper_button.iaMove = false
      temper_button.clickCount = 0
      temper_button.isSecondAudio = false
      temper_button.on('pointerdown', temperButtonDown)
      temper_button.on('pointermove', temperButtonMove)
      temper_button.on('pointerup', temperButtonUp)
      temper_button.zIndex = 2
      app.stage.addChild(temper_button)
    }
  }

  function temperButtonDown(event) {
    // TODO:温度按钮鼠标点下的事件
    let _this = this
    _this.isMove = true
    // 改变按钮点击的次数
    _this.clickCount++
    temperDeltaX = event.data.global.x - event.target.x
    temperDeltaY = event.data.global.y - event.target.y
    // 切换选中时候的纹理
    _this.texture =
      loader.resources[
        '../../images/rowimages_03/温度计滑块选中状态.png'
      ].texture
    // 播放点击音效
    playAudio('../../audio/L3/selected.mp3').then((resolve) => {
      resolve.addEventListener('ended', function () {
        playicon.css(toPlay)
      })
    })

    if (_this.clickCount == 1) {
      setTimeout(() => {
        _this.isSecondAudio = true
        _this.interactive = false
        tool_message.text = '小朋友，请将温度调到最右侧看看会发生什么吧!'
        playAudio('../../audio/L3/change_temper_max.mp3').then((resolve) => {
          resolve.addEventListener('ended', function () {
            playicon.css(toPlay)
            _this.interactive = true
          })
        })
      }, 5000)
    }
  }

  function temperButtonMove(event) {
    // TODO:温度按钮鼠标移动的事件
    let _this = this
    // 让调节器跟随鼠标移动
    if (_this.isMove) {
      if (_this.isSecondAudio) {
        // 1、判断当前的温度再哪一个范围呢
        // 2、如果当前的温度还在0——100 的范围内，指针可以任意移动
        // 3、如果当前的温度超出了100则控制移动的范围
        if (currentTemper(_this.y, _this) < 100) {
          buttonMoveMode_1(event, _this)
        }

        if (currentTemper(_this.y, _this) > 100) {
          buttonMoveMode_2(event, _this)
        }
      } else {
        buttonMoveMode_1(event, _this)
        // 判断是不是在温度计的范围内
      }
    }
  }

  // 指针可以在整个温度区域上调节
  function buttonMoveMode_1(event, _this) {
    if (event.data.global.y - temperDeltaY < temper.y) {
      // 当鼠标移动到温度计低温以外
      _this.y = temper.y
    } else if (
      event.data.global.y + (_this.height - temperDeltaY) >
      temper.y + temper.height
    ) {
      // 当鼠标移动到温度计高温以外
      _this.y = temper.y + temper.height - _this.height
    } else {
      // 当鼠标在温度计之内移动
      _this.y = event.data.global.y - temperDeltaY
      // TODO:调用是个方法来判读温度计现在在什么温度。
      let current_centigrade = currentTemper(_this.y, _this)
      // TODO:目前的话提过的变化过程的图片太少了，无法形成动画。
      if (current_centigrade < 0) {
        plate.texture =
          loader.resources['../../images/rowimages_03/盘子和冰.png'].texture
      } else if (0 < current_centigrade && current_centigrade < 100) {
        plate.texture =
          loader.resources[
            '../../images/rowimages_03/盘子和融化的冰.png'
          ].texture
      } else if (100 < current_centigrade && current_centigrade < 106) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水1.png'].texture
      } else if (106 < current_centigrade && current_centigrade < 112) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水2.png'].texture
      } else if (112 < current_centigrade && current_centigrade < 118) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水3.png'].texture
      } else {
        plate.texture =
          loader.resources['../../images/rowimages_03/空盘子.png'].texture
      }
    }
  }

  // 温度只能在大于10摄氏度的区域调节
  function buttonMoveMode_2(event, _this) {
    temper_mask.visible = true
    if (
      event.data.global.y - temperDeltaY <
      hundred_line.y - _this.height / 2
    ) {
      // 当鼠标移动到温度计低温以外
      _this.y = hundred_line.y - _this.height * 0.4
    } else if (
      event.data.global.y + (_this.height - temperDeltaY) >
      temper.y + temper.height
    ) {
      // 当鼠标移动到温度计高温以外
      _this.y = temper.y + temper.height - _this.height
    } else {
      // 当鼠标在温度计之内移动
      _this.y = event.data.global.y - temperDeltaY
      // TODO:调用是个方法来判读温度计现在在什么温度。
      let current_centigrade = currentTemper(_this.y, _this)
      // TODO:目前的话提过的变化过程的图片太少了，无法形成动画。
      if (current_centigrade < 0) {
        plate.texture =
          loader.resources['../../images/rowimages_03/盘子和冰.png'].texture
      } else if (0 < current_centigrade && current_centigrade < 100) {
        plate.texture =
          loader.resources[
            '../../images/rowimages_03/盘子和融化的冰.png'
          ].texture
      } else if (100 < current_centigrade && current_centigrade < 106) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水1.png'].texture
      } else if (106 < current_centigrade && current_centigrade < 112) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水2.png'].texture
      } else if (112 < current_centigrade && current_centigrade < 118) {
        plate.texture =
          loader.resources['../../images/rowimages_03/水3.png'].texture
      } else {
        plate.texture =
          loader.resources['../../images/rowimages_03/空盘子.png'].texture
        _this.interactive = false
        tool_message.text = '咦？为什么温度超过100度以后，水就消失了呢？'
        playAudio('../../audio/L3/asking_question.mp3').then((resolve) => {
          resolve.addEventListener('ended', function () {
            playicon.css(toPlay)
            _this.interactive = true
            // 当提问完毕之后页面显示出我们的录音控件
            $('#record').css({
              display: 'block',
            })
          })
        })
      }
    }
  }

  function temperButtonUp(event) {
    // TODO:温度按钮鼠标抬起的事件
    let _this = this
    _this.isMove = false
    _this.texture =
      loader.resources[
        '../../images/rowimages_03/温度计滑块未选中状态.png'
      ].texture
  }

  // 判断当前的温度值。
  function currentTemper(params, sprite) {
    params = params + sprite.height / 2
    let pre_centigrade = (hundred_line.y - zero_line.y) / 100
    let current_centigrde = (params - zero_line.y) / pre_centigrade
    return current_centigrde
  }

  // 设置0摄氏度
  function createZeroTempSprite() {
    loader.load(zeroTemperSetup)
    function zeroTemperSetup() {
      zero_temper = new PIXI.Text('0℃', {
        fontFamily: 'Arial',
        fontSize: (windowWidth * 23) / DESIGN_HEIGHT,
        align: 'center',
      })
      zero_temper.rotation = Math.PI / 2
      zero_temper.x = (windowWidth * 40) / DESIGN_HEIGHT
      zero_temper.y = (windowHeight * 283) / DESIGN_WIDTH
      app.stage.addChild(zero_temper)
    }
  }
  // 设置100摄氏度
  function createHundredSprite() {
    loader.load(zeroTemperSetup)
    function zeroTemperSetup() {
      hundred_temper = new PIXI.Text('100℃', {
        fontFamily: 'Arial',
        fontSize: (windowWidth * 23) / DESIGN_HEIGHT,
        align: 'center',
      })
      hundred_temper.rotation = Math.PI / 2
      hundred_temper.x = (windowWidth * 40) / DESIGN_HEIGHT
      hundred_temper.y = (windowHeight * 1000) / DESIGN_WIDTH
      app.stage.addChild(hundred_temper)
    }
  }

  // 绘制零度和一百度的刻度线
  function createTemperLine() {
    // TODO: 绘制零度和一百度的刻度线
    loader.load(zeroLineSetup)
    function zeroLineSetup() {
      zero_line = new PIXI.Sprite(
        loader.resources['../../images/rowimages_03/刻度条.png'].texture
      )
      zero_line.width = (windowWidth * 37) / DESIGN_HEIGHT
      zero_line.height = (windowHeight * 1) / DESIGN_WIDTH
      zero_line.x = (windowWidth * 59) / DESIGN_HEIGHT
      zero_line.y = (windowHeight * 300) / DESIGN_WIDTH

      app.stage.addChild(zero_line)
    }

    loader.load(() => {
      hundred_line = new PIXI.Sprite(
        loader.resources['../../images/rowimages_03/刻度条.png'].texture
      )
      hundred_line.width = (windowWidth * 37) / DESIGN_HEIGHT
      hundred_line.height = (windowHeight * 1) / DESIGN_WIDTH
      hundred_line.x = (windowWidth * 59) / DESIGN_HEIGHT
      hundred_line.y = (windowHeight * 1033) / DESIGN_WIDTH
      app.stage.addChild(hundred_line)
    })
  }

  // 100℃以下区域的灰色遮罩
  function createTemperMsek() {
    let x = (windowWidth * 50) / DESIGN_HEIGHT
    let y = (windowHeight * 118) / DESIGN_WIDTH
    let width = (windowWidth * 57) / DESIGN_HEIGHT
    let height = (windowHeight * (1033 - 118)) / DESIGN_WIDTH
    temper_mask = new PIXI.Graphics()
    temper_mask.beginFill(0x000000)
    temper_mask.drawRect(x, y, width, height)
    temper_mask.endFill()
    temper_mask.alpha = 0.3
    temper_mask.zIndex = 1
    temper_mask.visible = false
    app.stage.addChild(temper_mask)
  }

  function createToolMessage() {
    // TODO: 这里创建的是工具框中的说明文字
    tool_message = new PIXI.Text('小朋友，请调节温度来观察冰块的变化吧！', {
      fontSize: (windowWidth * 36) / DESIGN_HEIGHT,
    })
    tool_message.rotation = Math.PI / 2
    tool_message.y = (windowHeight - tool_message.width) / 2
    tool_message.x = (windowWidth * 557) / DESIGN_HEIGHT
    tool_message.zIndex = 1
    app.stage.addChild(tool_message)
  }

  function gameLoop() {
    requestAnimationFrame(gameLoop)
    state()
    tink.update()
    app.renderer.render(app.stage)
  }

  async function playAudio(url) {
    if (audio) {
      audio.pause()
    }
    // let audio;
    audio = new Audio(url)
    playicon.css(playing)
    audio.play()
    if (url != '../../audio/L3/selected.mp3') {
      currentAudioUrl = url
    }
    return audio
  }

  function play() {}

  //-------------对页面的顶端返回条进行设置--------------
  let backbar = $('#backbar')
  backbar.css({
    width: windowHeight,
    height: (windowWidth * 114) / DESIGN_HEIGHT,
    'line-height': (windowWidth * 114) / DESIGN_HEIGHT + 'px',
    transform: 'rotate(90deg)',
    'transform-origin': '0% 0%',
    top: 0,
    left: windowWidth,
  })

  let backbutton = $('#backbutton')
  backbutton.css('line-height', (windowWidth * 114) / DESIGN_HEIGHT + 'px')
  backbutton.css('width', backbutton.height())
  backbutton.css('text-align', 'center')
  backbutton.on('click', function (e) {
    e.stopPropagation()
    location.href = '../../index.html'
  })

  let backtitle = $('#backtitle')
  backtitle.css('line-height', (windowWidth * 80) / DESIGN_HEIGHT + 'px')

  let playicon = $('#playicon')
  playicon.css('width', (windowWidth * 80) / DESIGN_HEIGHT + 'px')
  playicon.on('click', function (e) {
    e.stopPropagation()
    playAudio(currentAudioUrl).then((resolve) => {
      resolve.addEventListener('ended', function () {
        playicon.css(toPlay)
      })
    })
  })

  // 对实验的遮罩层进行设置
  let shadowPanel = $('.shadowPanel')
  shadowPanel.hide()
  shadowPanel.css({
    width: windowHeight,
    height: windowWidth,
    'transform-origin': '0% 0%',
    left: windowWidth,
  })

  // 获取再看一遍的按钮
  let replay = $('.replay')
  replay.bind('click', function (e) {
    location.href = ''
    shadowPanel.hide()
    playAudio('../../audio/L1/三个皇冠拖入桶中.mp3').then((resolve) => {
      resolve.addEventListener('ended', function () {
        playicon.css(toPlay)
      })
    })
  })

  let nextItem = $('.nextItem')
  nextItem.bind('click', function (e) {
    window.location.replace('./course_report_01.html')
    shadowPanel.hide()
  })

  initApp()
  playAudio('../../audio/L3/change_temper.mp3').then((resolve) => {
    resolve.addEventListener('ended', function () {
      playicon.css(toPlay)
      temper_button.interactive = true
    })
  })
  gameLoop()
}
